package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.fishingwithme.android.data.model.CirclePageDto
import com.fishingwithme.android.data.model.City
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CircleViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {
    
    private var currentTitle: String? = null
    private var currentCityCode: String? = null
    private var currentIsActive: Boolean? = null

    fun getCircles(
        title: String? = null,
        cityCode: String? = null,
        isActive: Boolean? = null
    ): Flow<PagingData<CirclePageDto>> {
        // Update current search parameters
        currentTitle = title
        currentCityCode = cityCode
        currentIsActive = isActive
        
        return Pager(
            config = PagingConfig(
                pageSize = 20,
                enablePlaceholders = false
            ),
            pagingSourceFactory = {
                CirclePagingSource(repository, title, cityCode, isActive)
            }
        ).flow.cachedIn(viewModelScope)
    }
    
    // Method to refresh with current parameters
    fun refreshCircles(): Flow<PagingData<CirclePageDto>> {
        return getCircles(currentTitle, currentCityCode, currentIsActive)
    }
    
    // Search cities functionality
    fun searchCities(keyword: String, onResult: (List<City>) -> Unit) {
        viewModelScope.launch {
            try {
                val result = repository.searchCities(keyword).first()
                result.fold(
                    onSuccess = { cities ->
                        onResult(cities)
                    },
                    onFailure = { 
                        // Handle error case
                        onResult(emptyList())
                    }
                )
            } catch (e: Exception) {
                // Handle exception
                onResult(emptyList())
            }
        }
    }
}